import { defineStore } from 'pinia'
import { getProducts, IProduct } from '../api/shop'

export const useProdunctsStore = defineStore('products', {
  state: () => {
    return {
      all: [] as IProduct[], // 所有商品列表（学习类型断言的使用）
    }
  },

  getters: {},

  actions: {
    //actions既支持异步操作
    async loadAllProducts() {
      const ret = await getProducts()
      this.all = ret
    },
    // 也支持同步操作
    decrementProduct(product: IProduct) {
      const ret = this.all.find((item) => item.id === product.id)
      if (ret) {
        ret.inventory--
      }
    },
    addProduct(product: IProduct) {
      const ret = this.all.find((item) => item.id === product.id)
      if (ret) {
        ret.inventory++
      }
    },
  },
})
